package com.lac.component.controller;

import com.lac.component.dao.GoodsSpuOperationLogChangeMapper;
import com.lac.component.model.GoodsSpuOperationLogChange;
import com.lac.component.utils.OSSUrlUploader;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * @author xiaokuixiao
 * date2025/7/31 14:29
 */
@RestController
@Slf4j
public class GoodsSpuOperationLogChangeController {
    @Autowired
    private GoodsSpuOperationLogChangeMapper  goodsSpuOperLogChangeMapper;

    @GetMapping("/value")
    public String   draftJson() {
        StringBuffer combinedSql = new StringBuffer();
        StringBuffer deleteCombinedSql = new StringBuffer();
        List<GoodsSpuOperationLogChange> goodsSpuOperationLogChanges = goodsSpuOperLogChangeMapper.getGoodsSpuOperationLogChange();
//        goodsSpuOperationLogChanges = goodsSpuOperationLogChanges.stream().limit(3).collect(Collectors.toList());
        List<String> idList = new ArrayList<>();
        List<String> serverNamesMutable = new ArrayList<>(Arrays.asList("wm-dev-b1", "wm-prod-b1", "em-dev-b1", "em-prod-b1","https://siwmstatic.ecej.com"));        String url = "wm-prod-b1.oss-cn-beijing.aliyuncs.com/common/video";
        // 遍历所有需要处理的商品，或者只处理第一个/特定id的
        // 这里只是示例，通常你会有一个循环
        for (int i = 0; i < goodsSpuOperationLogChanges.size(); i++) {
            GoodsSpuOperationLogChange goodsSpuOperationLogChange = goodsSpuOperationLogChanges.get(i);
            String OldDraftJson = goodsSpuOperationLogChange.getOldValue();
            String newDraftJson = checkAndReuploadResources(OldDraftJson, serverNamesMutable);


            String OldReleaseJson = goodsSpuOperationLogChange.getNewValue();
            String newReleaesJson = checkAndReuploadResources(OldReleaseJson, serverNamesMutable);
            if (newDraftJson != null && newReleaesJson != null&& !newDraftJson.equals("") &&!newReleaesJson.equals("")) {
                // 比较新旧JSON字符串，避免不必要的更新
                if (!newDraftJson.equals(OldDraftJson) && !newReleaesJson.equals(OldReleaseJson)) {
                    String escapedDraftJson = newDraftJson.replace("'", "''"); // 简单的单引号转义
                    String replaceReleaesJson = newReleaesJson.replace("'", "''");
                    String goodsSpuId = goodsSpuOperationLogChange.getId().replace("'", "''"); // 简单的单引号转义

                    String updateSql = String.format("UPDATE `oms_mall`.`goods_spu_operation_log_change` SET `%s` = '%s' , `%s` = '%s' WHERE  `id` = '%s';", "old_value", escapedDraftJson, "new_value", replaceReleaesJson, goodsSpuId);
                    // 构建SQL更新语句
//                String updateSql = buildUpdateSql(goodsSpuChannel.getId(), newDraftJson, "draft_json");

                    combinedSql.append(updateSql).append("\n");

                    String deleteSql = buildDeleteSql(goodsSpuOperationLogChange.getId());

                    deleteCombinedSql.append(deleteSql).append("\n");
                } else if (!newDraftJson.equals(OldDraftJson) && newReleaesJson.equals(OldReleaseJson)) {
                    String updateSql = buildUpdateSql(goodsSpuOperationLogChange.getId(), newDraftJson, "old_value");

                    combinedSql.append(updateSql).append("\n");

                    String deleteSql = buildDeleteSql(goodsSpuOperationLogChange.getId());

                    deleteCombinedSql.append(deleteSql).append("\n");
                } else if (newDraftJson.equals(OldDraftJson) && !newReleaesJson.equals(OldReleaseJson)) {
                    String updateSql = buildUpdateSql(goodsSpuOperationLogChange.getId(), newReleaesJson, "new_value");

                    combinedSql.append(updateSql).append("\n");

                    String deleteSql = buildDeleteSql(goodsSpuOperationLogChange.getId());

                    deleteCombinedSql.append(deleteSql).append("\n");
                } else {
                    idList.add(goodsSpuOperationLogChange.getId());
                    System.out.println("GoodsSpu ID: " + goodsSpuOperationLogChange.getId() + " 的图片URL没有变化，无需更新。");
                }
                log.info("条数============================================={}", i + 1);
            } else if (newDraftJson != null && !newDraftJson.equals("")) {
                if (!newDraftJson.equals(OldDraftJson)) {
                    String updateSql = buildUpdateSql(goodsSpuOperationLogChange.getId(), newDraftJson, "old_value");

                    combinedSql.append(updateSql).append("\n");

                    String deleteSql = buildDeleteSql(goodsSpuOperationLogChange.getId());

                    deleteCombinedSql.append(deleteSql).append("\n");
                } else {
                    idList.add(goodsSpuOperationLogChange.getId());
                    System.out.println("GoodsSpu ID: " + goodsSpuOperationLogChange.getId() + " 的图片URL没有变化，无需更新。");
                }
            } else if (newReleaesJson != null && !newReleaesJson.equals("")) {
                if (!newReleaesJson.equals(OldReleaseJson)) {
                    String updateSql = buildUpdateSql(goodsSpuOperationLogChange.getId(), newReleaesJson, "new_value");

                    combinedSql.append(updateSql).append("\n");

                    String deleteSql = buildDeleteSql(goodsSpuOperationLogChange.getId());

                    deleteCombinedSql.append(deleteSql).append("\n");
                } else {
                    idList.add(goodsSpuOperationLogChange.getId());
                    System.out.println("GoodsSpu ID: " + goodsSpuOperationLogChange.getId() + " 的图片URL没有变化，无需更新。");
                }
            }

        }
        log.info("combinedSql:{}", combinedSql);
        if (idList.size() > 0) {
            String goodsSpuId = String.join(",", idList);
            String selectSql = "SELECT * FROM `oms_mall`.`goods_spu_operation_log_change` WHERE `id` IN (" + goodsSpuId + ");";
            String string = combinedSql.append(deleteCombinedSql).append(selectSql).toString();
            log.info("selectSql:{}", string);
            return string;
        } else {
            String string = combinedSql.append(deleteCombinedSql).toString();
            log.info("selectSql:{}", string);
            return string;
        }
    }
    /**
     * 检查并重新上传图片到OSS
     * @param htmlContent 包含图片URL的HTML内容
     * @param serverNames 需要重新上传的服务器名称列表
     * @return 更新后的HTML内容
     */
    public static String checkAndReuploadResources(String htmlContent, List<String> serverNames) {
        if (StringUtils.isBlank(htmlContent)) {
            return htmlContent;
        }

        // 同时匹配img和video标签的src属性
        String regex = "<(img|video)[^>]+?src\\s*=\\s*[\"']?([^\"'\\s>]+)[\"']?";
        Pattern pattern = Pattern.compile(regex);
        Matcher matcher = pattern.matcher(htmlContent);
        StringBuffer result = new StringBuffer();

        while (matcher.find()) {
            String fullTag = matcher.group(0);   // 完整标签
            String tagType = matcher.group(1);    // 标签类型（img或video）
            String resourceUrl = matcher.group(2); // 资源URL

            log.info("处理{}标签: {}, URL: {}", tagType, fullTag, resourceUrl);

            // 检查是否需要重新上传
            boolean needReupload = false;
            for (String serverName : serverNames) {
                if (resourceUrl.contains(serverName)) {
                    log.info("URL 包含 serverName {}, 不重新上传", serverName);
                    needReupload = true;
                    break;
                }
            }

            String newResourceUrl = resourceUrl;
            if (!needReupload && StringUtils.isNotBlank(resourceUrl) && resourceUrl.startsWith("http")) {
                try {
                    // 根据资源类型选择上传目录
                    String uploadPath = "img".equals(tagType)
                            ? "common/material"
                            : "common/video";

                    newResourceUrl = OSSUrlUploader.uploadFromUrlWithSnowflakeName(resourceUrl, uploadPath);
                } catch (Exception e) {
                    log.error("重新上传{}失败: {}", tagType, resourceUrl, e);
                }
            } else {
                log.info("跳过处理: needReupload={}, isHttp={}", needReupload, resourceUrl.startsWith("http"));
            }

            // 替换标签中的URL
            String newTag = fullTag.replace(resourceUrl, newResourceUrl);
            matcher.appendReplacement(result, Matcher.quoteReplacement(newTag));
            log.info("替换后的{}标签：{}", tagType, newTag);
        }
        matcher.appendTail(result);
        return result.toString();
    }


    /**
     * 构建SQL UPDATE语句的辅助方法
     * @param goodsSpuId 商品ID
     * @param newPicUrlsJson 新的图片URL JSON字符串
     * @return SQL UPDATE语句
     */
    private String buildUpdateSql(String  goodsSpuId, String newPicUrlsJson ,String featureName) {
        // 注意：实际生产环境中，请使用PreparedStatement防止SQL注入！
        // 这里的拼接仅用于演示生成的SQL字符串。

        // 为了SQL安全，需要对newPicUrlsJson进行适当的转义，特别是单引号
        // 通常数据库驱动或ORM框架会自动处理
        String escapedNewPicUrlsJson = newPicUrlsJson.replace("'", "''"); // 简单的单引号转义
        goodsSpuId = goodsSpuId.replace("'", "''"); // 简单的单引号转义

        return String.format(
                "UPDATE `oms_mall`.`goods_spu_operation_log_change` SET `%s` = '%s' WHERE `id` = '%s';",
                featureName, escapedNewPicUrlsJson,
                goodsSpuId
        );
    }

    /**
     * 构建SQL DELETE语句的辅助方法
     * @param goodsSpuId 商品ID
     * @return SQL DELETE语句
     */
    private String buildDeleteSql(String  goodsSpuId) {
        return String.format("DELETE FROM `oms_mall`.`goods_spu_operation_log_change` WHERE `id` = %s;","'"+goodsSpuId+"'");
    }


}


